package com.springframework.boot.common.user.service.impl;

import com.springframework.boot.common.perms.entity.Perms;
import com.springframework.boot.common.roles.entity.Role;
import com.springframework.boot.common.user.entity.User;
import com.springframework.boot.common.user.mapper.UserMapper;
import com.springframework.boot.common.user.service.UserService;
import com.springframework.boot.common.utils.CommonUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;
    @Override
    public void register(User user) {
        try {
            //1、生成随机盐
            String randomSalt = CommonUtils.getRandomSalt(8);
            //将随机盐保存到数据库
            user.setSalt(randomSalt);
            //3、明文密码进行MD5+salt+hash散列
            Md5Hash md5Hash = new Md5Hash(user.getPassword(),randomSalt,1024);
            user.setPassword(md5Hash.toHex());
            userMapper.save(user);
        }catch (Exception e){
            System.out.println("保存失败");
             e.printStackTrace();
        }

    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.getUserByUsername(username);
    }

    @Override
    public User getRolesByUsername(String username) {
        return userMapper.getRolesByUsername(username);
    }

    @Override
    public List<Perms> getPermsByRoleId(String roleId) {
        return userMapper.getPermsByRoleId(roleId);
    }
}
